package handler

import (
	"class/glodal"
	"class/model"
	"class/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"strconv"
)

type ChatHandler struct {
}

func (h ChatHandler) Chat(c *gin.Context) {
	UserId, err := strconv.ParseInt(c.Query("userId"), 10, 64)
	if err != nil {
		return
	}
	conn, err := glodal.Upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	node := glodal.Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}
	glodal.CliMap[int(UserId)] = node
	go func(node glodal.Node) {
		for {
			_, message, err := node.Conn.ReadMessage()
			if err != nil {
				return
			}
			var msg model.Message
			err = json.Unmarshal(message, &msg)
			if err != nil {
				return
			}
			if n, ok := glodal.CliMap[int(msg.DistId)]; ok {
				n.Data <- message
			}
			
			rabbitmq := pkg.NewRabbitMQSimple("course")
			rabbitmq.PublishSimple(string(message))
		}
	}(node)
	go func(node glodal.Node) {
		for {
			data := <-node.Data
			err := node.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				return
			}
		}
	}(node)
}
func NewChatHandler() *ChatHandler {
	return &ChatHandler{}
}
